package com.hzit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hzit.entity.Classes;
import com.hzit.entity.PageResult;
import com.hzit.entity.Student;
import com.hzit.mapper.ClassesMapper;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.IStudentService;
import com.hzit.dto.StudentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class StudentServiceImpl implements IStudentService {
	@Autowired
	private StudentMapper studentMapper;
	@Autowired
	private ClassesMapper classesMapper;
	//1. 查询所有学生列表
	@Override
	public List<StudentDTO> findAll() {
		//1.1 查询出学生列表
		List<Student> students = studentMapper.findAll();
		//1.2 遍历学生列表
		List<StudentDTO> collect = students.stream().map(m -> {
			//1.2.1 定义vo对象
			StudentDTO vo = new StudentDTO();
			//1.2.2 拷贝属性到vo对象中
			BeanUtil.copyProperties(m, vo, true);
			//1.2.3 根据班级id查询出班级对象
			Classes classes = classesMapper.findById(m.getCid());
			//1.2.4 为当前的vo对象设置班级名称
			vo.setCname(classes.getCname());
			return vo;
		}).collect(Collectors.toList());
		return collect;
	}

	//2. 分页查询
	@Override
	public PageResult<StudentDTO> findPage(int page, int pageSize) {
		//2.1 开始分页
		PageHelper.startPage(page,pageSize);
		//2.2 开始查询
		List<Student> studentVos = studentMapper.findAll();
		//2.3 将上面的集合转换为 Page对象
		Page<Student> studentVoPage = (Page<Student>) studentVos;
		List<Student> result = studentVoPage.getResult();
		//2.4 将上面的集合处理成vo集合对象
		List<StudentDTO> collect = result.stream().map(m -> {
			//1.2.1 定义vo对象
			StudentDTO vo = new StudentDTO();
			//1.2.2 拷贝属性到vo对象中
			BeanUtil.copyProperties(m, vo, true);
			//1.2.3 根据班级id查询出班级对象
			Classes classes = classesMapper.findById(m.getCid());
			//1.2.4 为当前的vo对象设置班级名称
			vo.setCname(classes.getCname());
			return vo;
		}).collect(Collectors.toList());

		//2.5 将上面的page对象转换为PageResult
		return new PageResult<>(collect,studentVoPage.getTotal());
	}
}
